﻿using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// <summary>
/// Plays the specified sound.
/// </summary>

[AddComponentMenu("UGUI/Interaction/Play Sound")]
public class UGUIPlaySound : MonoBehaviour, IPointerUpHandler, IPointerDownHandler, IPointerEnterHandler, IPointerExitHandler, ISelectHandler, IDeselectHandler
{
	public enum Trigger
	{
		OnClick,
		OnMouseOver,
		OnMouseOut,
		OnPress,
		OnRelease,
		Custom,
		OnEnable,
		OnDisable,
	}

	public AudioClip audioClip;
	public Trigger trigger = Trigger.OnClick;

	[Range(0f, 1f)] public float volume = 1f;
	[Range(0f, 2f)] public float pitch = 1f;

	bool mIsOver = false;

	bool canPlay
	{
		get
		{
			if (!enabled) return false;
			Button btn = GetComponent<Button>();
			return (btn == null || btn.IsActive());
		}
	}

	void OnEnable ()
	{
        if (trigger == Trigger.OnEnable)
        {
            UGUITools.PlaySound(audioClip, volume, pitch);
        }
	}

	void OnDisable ()
	{
        if (trigger == Trigger.OnDisable)
        {
            UGUITools.PlaySound(audioClip, volume, pitch);
        }
	}

	void OnHover (bool isOver)
	{
		if (trigger == Trigger.OnMouseOver)
		{
			if (mIsOver == isOver) return;
			mIsOver = isOver;
		}

        if (canPlay && ((isOver && trigger == Trigger.OnMouseOver) || (!isOver && trigger == Trigger.OnMouseOut)))
        {
            UGUITools.PlaySound(audioClip, volume, pitch);
        }
	}

	void OnPress (bool isPressed)
	{
		if (trigger == Trigger.OnPress)
		{
			if (mIsOver == isPressed) return;
			mIsOver = isPressed;
		}

        if (canPlay && ((isPressed && trigger == Trigger.OnPress) || (!isPressed && trigger == Trigger.OnRelease)))
        {
            UGUITools.PlaySound(audioClip, volume, pitch);
        }
	}

    void OnSelect(bool isSelected)
    {
        if (canPlay)
        {
            OnHover(isSelected);
        }
    }

    public void Play ()
	{
		UGUITools.PlaySound(audioClip, volume, pitch);
	}

    #region UGUI Event Handlers

    public void OnPointerUp(PointerEventData eventData)
    {
        OnPress(false);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        OnPress(true);
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        OnHover(true);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        OnHover(false);
    }

    public void OnSelect(BaseEventData eventData)
    {
        OnSelect(true);
    }

    public void OnDeselect(BaseEventData eventData)
    {
        OnSelect(false);
    }

    #endregion
}
